package com.xpsoft.oa.workflow.event;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.api.model.OpenProcessInstance;

import com.xpsoft.core.util.AppUtil;
import com.xpsoft.oa.model.flow.ProcessRun;
import com.xpsoft.oa.model.produce.MaterialPurchaseAdjust;
import com.xpsoft.oa.model.system.AppUser;
import com.xpsoft.oa.service.flow.ProcessRunService;
import com.xpsoft.oa.service.produce.MaterialPurchaseAdjustService;
import com.xpsoft.oa.service.produce.MaterialPurchaseService;
import com.xpsoft.oa.service.system.AppUserService;

public class MaterialPurchaseAdjustFinishListener implements EventListener{
	private Log logger=LogFactory.getLog(MaterialPurchaseAdjustFinishListener.class);
	@Override
	public void notify(EventListenerExecution execution) throws Exception {
		//获取表单参数
		OpenProcessInstance pi=execution.getProcessInstance();
		String userId = (String)pi.getVariable("materialPurchaseAdjust.createUser.userId");
		Date createTime = (Date)pi.getVariable("materialPurchaseAdjust.createTime");
		String purchaseId = (String)pi.getVariable("materialPurchaseAdjust.materialPurchase.id");
		String applyReason = (String)pi.getVariable("materialPurchaseAdjust.applyReason");
		String dataList = (String)pi.getVariable("materialPurchaseAdjust.dataList");
		
		MaterialPurchaseAdjust materialPurchaseAdjust = new MaterialPurchaseAdjust();
		materialPurchaseAdjust.setCreateTime(createTime);
		materialPurchaseAdjust.setAdjustDate(createTime);
		materialPurchaseAdjust.setApplyReason(applyReason);
		
		if(StringUtils.isNotBlank(purchaseId)){
			MaterialPurchaseService materialPurchaseService = (MaterialPurchaseService)AppUtil.getBean("materialPurchaseService");
			materialPurchaseAdjust.setMaterialPurchase(materialPurchaseService.get(Long.valueOf(purchaseId)));
		}
		
		if(StringUtils.isNotBlank(userId)){
			AppUserService appUserService = (AppUserService)AppUtil.getBean("appUserService");
			materialPurchaseAdjust.setCreateUser(appUserService.get(Long.valueOf(userId)));
		}
		
		ProcessRunService processRunService=(ProcessRunService)AppUtil.getBean("processRunService");
		ProcessRun processRun=processRunService.getByExeId(pi.getId());
		materialPurchaseAdjust.setProcessRunId(processRun.getRunId());
		
		MaterialPurchaseAdjustService materialPurchaseAdjustService = (MaterialPurchaseAdjustService)AppUtil.getBean("materialPurchaseAdjustService");
		materialPurchaseAdjustService.saveMaterialPurchaseAdjust(materialPurchaseAdjust, dataList);
		
		
		//获取流程发起者对象
		AppUser flowStartUser=(AppUser)execution.getProcessInstance().getVariable("flowStartUser");
	
		//所有参与流程的都发消息
		AppUtil.sendSysShortMsg(execution.getProcessInstance().getId(), flowStartUser);
	}

}
